<?php

namespace App\Http\Controllers\WeChat;


use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use \Illuminate\Contracts\Session\Session;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Redirect;
use Request;
use App\Common\Response;

class WechatController extends Controller
{

    public function serve()
    {
        Log::info( 'request arrived.' );
        $app     = app( 'EasyWeChat' );
        $oauth   = $app->officialAccount()->oauth;
        $user    = $oauth->user()->toArray();
        $session = Session();
        $session->put( "wechat_user",$user );
        $target_url = $session->get( "target_url" );

        return Redirect::to( $target_url );
        //
        //        $app->officialAccount()->template_message->send([
        //            'touser' => $user['id'],
        //            'template_id' => '-nIcmmownfHmTHjsCWAjrwGjXQIk8CleQyBJLJUvsxI',
        //            'data' => [
        //                'key1' => 'WDEJC123454',
        //                'key2' => '辽宁省大连市软件园8号',
        //                'key3' => '2018-07-19 09:50',
        //                'key4' => '缺水',
        //            ]
        //
        //        ]);


    }


    /**IP 用户绑定微信账户
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */

    public function login()
    {
        Log::info( 'request arrived.' );
        $app     = app( 'EasyWeChat' );
        $session = Session();
        $user    = $session->get( "wechat_user" );
        if (empty( $user )){
            $oauth      = $app->officialAccount()->oauth;
            $target_url = "WeChat/wechatService/login";
            $session->put( "target_url",$target_url );

            return $oauth->redirect();

        }
        $where_use=[
             'wechat'  => $user[ 'id' ]
        ];
         $userModel = User::where( $where_use )->first();
         
         if(!empty($userModel)){
              return  Redirect::route('WeChat.wechatService.unbind', [ "account" => $userModel[ 'account' ],"account_id" => $userModel[ 'id' ] ])  ;    
         }else{
           return view( "wechat/login" );
         }
    }

    public function unbind()
    {
        $request = Request::all();
        $session = Session();
        $user    = $session->get( "wechat_user" );
        $account = $session->get( "account" );
        $data    = [
            "userInfo"   => $user,
            "account"    => $request[ 'account' ],
            "account_id" => $request[ 'account_id' ],
        ];

        return view( "wechat/unbind",$data );
    }


    public function doUnbind()
    {

        $request   = Request::all();
        $where_use = [
            "id" => $request[ 'account_id' ],
        ];
        $userModel = User::where( $where_use )->first();
        if (!empty( $userModel )){
            $userModel[ 'wechat' ] = "";
            if ($userModel->save()){
                return Response::show( 0,"解除绑定成功" );
            }
            else{
                return Response::show( 1,"解除绑定失败,操作失败，请重新解除绑定" );
            }
        }
        else{
            return Response::show( 2,"解除绑定失败" );
        }


    }

    public function weChat_detail()
    {
        $request       = Request::all();
        $id            = $request[ 'id' ];
        $with_product  = [
            "ProgressState",
            "FirstType",
            "SecondType",
            "Files",
            "Progress"  => function ($query){
                $query->orderBy( "id" );
            },
            "Operation" => function ($query){
                $query->orderBy( "id","desc" );
            },
        ];
        $where_product = [
            "id" => $id,
        ];
        $productModel  = Product::with( $with_product )->where( $where_product )->first();
        if (!empty( $productModel )){
            $product = $productModel->toArray();
        }
        else{
            $product = [];
        }
        $returnData = [ 'product' ];

        return view( "wechat/weChat_detail",compact( $returnData ) );
    }

    public function bindAccount()
    {
        $request = Request::all();
        $session = Session();
        $session->put( "account",$request[ 'account' ] );
        $user      = $session->get( "wechat_user" );
        $where_use = [ "account" => $request[ 'account' ],"password" => md5( $request[ 'password' ] ),
        ];
        $userModel = User::where( $where_use )->first();
        if (!empty( $userModel )){
            $userModel[ 'wechat' ] = $user[ 'id' ];
            if ($userModel->save()){
                return Response::show( 0,"绑定成功",[ "account" => $request[ 'account' ],"account_id" => $userModel[ 'id' ] ] );
            }
            else{
                return Response::show( 1,"绑定失败,操作失败，请重新绑定" );
            }
        }
        else{
            return Response::show( 2,"绑定失败，用户名或密码错误！" );
        }


    }

    public static function updateProgressNotice($id)
    {

        $where_product = [
            "id" => $id,
        ];
        $with_product  = [
            "Operation" => function ($query){
            $query->orderBy( "id","desc" )->first();
            },
            "User",
        ];
        $productModel  = Product::with( $with_product )->where( $where_product )->first();
        if (!empty( $productModel )){
            $product         = $productModel->toArray();
            $officialAccount = app( 'EasyWeChat' )->officialAccount();

            if (!empty( $product[ 'user' ][ 'wechat' ] )){
                $officialAccount->template_message->send( [
                    'touser'      => $product[ 'user' ][ 'wechat' ],
                    'template_id' => 'IriDC63VoJr_uPU-57OBqgqZZNdbGNOqEvGKGGybeKI',
                    'url'         => 'http://www.ipoperate.com/WeChat/wechatService/weChat_detail?id=161http://process.ipoperate.com/WeChat/wechatService/weChat_detail?id='.$id,
                    'data'        => [
                        "first"    => "尊敬的" . $product[ 'user' ][ 'real_name' ] . "您的任务进度已更新，请注意查收。",
                        "keyword1" => $product[ 'name' ],
                        "keyword2" => $product[ 'operation' ][ 0 ][ 'content' ],
                        "keyword3" => $product[ 'operation' ][ 0 ][ 'operator_name' ],
                        "keyword4" => date( "Y-m-d H:i",strtotime( $product[ 'operation' ][ 0 ][ 'created_at' ] ) ),
                        "remark"   => '请及时查看消息',
                    ],
                ] );
            }


            return Response::show( 0,"操作成功",[] );
        }else{
            return Response::show( 1,"失败，参数错误" );
        }

    }

}
